package org.jgs1904.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 解决跨域请求
 * 
 * @author junki
 * @date 2020年4月2日
 */
public class CrossFilter implements Filter {

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers", "Authentication");
		
		// 根据key判断是否允许请求
//		if (!"jgs1904".equals(request.getParameter("key"))) {
//			response.getWriter().print(JSON.toJSONString(ResultBean.builder().code("403").message("key无效").build()));
//			return;
//		}
		
		// 判断请求的ip地址
		System.out.println(request.getRemoteAddr());
		if (!"0:0:0:0:0:0:0:1".equals(request.getRemoteAddr())) {
			return;
		}
		
		filterChain.doFilter(servletRequest, servletResponse);

	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void destroy() {

	}
}